{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def decode_binary_data(data_hex):\n",
    "    # Convert the input hexadecimal string to a list of integers (bytes)\n",
    "    data = [int(byte, 16) for byte in data_hex.split()]\n",
    "    n = len(data)\n",
    "    \n",
    "    # Pointer to read the data\n",
    "    i = 0\n",
    "    total_length = 0\n",
    "    \n",
    "    while i < n:\n",
    "        if data[i] == 0xF0:  # Simple encoding unit\n",
    "            if i + 5 > n:  # Check if there's enough bytes for the full simple unit\n",
    "                return -1\n",
    "            # A simple unit is exactly 5 bytes (1 byte for TAG and 4 bytes for SINGLE-VALUE)\n",
    "            total_length += 4  # SINGLE-VALUE length is 4 bytes\n",
    "            i += 5  # Move the pointer to the next unit\n",
    "            \n",
    "        elif data[i] == 0xF1:  # Complex encoding unit\n",
    "            if i + 6 > n:  # Check if there's enough bytes for the tag, repeat, and LEN fields\n",
    "                return -1\n",
    "            repeat_count = data[i + 1]\n",
    "            length = int.from_bytes(data[i + 2:i + 6], byteorder='big')\n",
    "            i += 6  # Move the pointer past the tag, repeat, and LEN fields\n",
    "            \n",
    "            if i + length > n:  # Check if the length of the inner data fits\n",
    "                return -1\n",
    "            \n",
    "            # Recursively decode the inner encoding units\n",
    "            inner_length = decode_binary_data(' '.join(f'{byte:02X}' for byte in data[i:i + length]))\n",
    "            if inner_length == -1:\n",
    "                return -1\n",
    "            \n",
    "            total_length += repeat_count * inner_length\n",
    "            i += length  # Move the pointer to the next unit after the inner complex data\n",
    "            \n",
    "        else:\n",
    "            # Invalid tag\n",
    "            return -1\n",
    "    \n",
    "    return total_length\n",
    "\n",
    "# Test cases\n",
    "test_data_1 = \"F1 02 00 00 00 05 F0 01 02 03 04\"\n",
    "test_data_2 = \"F1 01 00 00 00 04 F0 01 05\"\n",
    "test_data_3 = \"F1 01 00 00 00 06 F0 00 00 00 03 03 03\"\n",
    "\n",
    "print(decode_binary_data(test_data_1))\n",
    "print(decode_binary_data(test_data_2))\n",
    "print(decode_binary_data(test_data_3))"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
